import React from 'react';
import Utils from './utils.js';

export default class TodoItem extends React.Component{
    constructor(props){
        super(props);
        this.state = {editText : props.todo.title};
        this.handleKeyDown = this.handleKeyDown.bind(this);
        this.handleChange = this.handleChange.bind(this);
        this.handleEdit = this.handleEdit.bind(this);
        this.textInput = React.createRef();
    }
    handleKeyDown(event) {
        if (event.which === Utils.ESCAPE_KEY) {
            this.setState({editText: this.props.todo.title});
            this.props.onCancel(event);
        } else if (event.which === Utils.ENTER_KEY) {
            this.handleSubmit();
        }
    }
    handleEdit() {
        this.props.onEdit();
        this.setState({editText: this.props.todo.title});
    }
    handleSubmit() {
        let val = this.state.editText.trim();
        if (val) {
            this.props.onSave(val);
        } else {
            this.props.onDestroy();
        }
    }    
    handleChange(event) {
        if (this.props.editing) {
            this.setState({editText: event.target.value});
        }
    }
    componentDidUpdate(prevProps) {
        if (!prevProps.editing && this.props.editing) {
            let node = this.textInput.current;
            node.focus();
            node.setSelectionRange(node.value.length, node.value.length);
        }
    }
    render(){
        let liClassString = '';
        if(this.props.todo.completed)
            liClassString += 'completed';
        if(this.props.editing)
            liClassString += this.props.todo.completed ? ' editing' : 'editing';
        return(
            <li className={liClassString}>
            <div className="view">
                <input
                    type="checkbox"
                    className="toggle"
                    checked={this.props.todo.completed}
                    onChange={this.props.onToggle}
                />                
                <label onDoubleClick={this.handleEdit}>{this.props.todo.title}
                </label>
                <button onClick={this.props.onDestroy} className="destroy destroy-button"></button>
            </div>
            <input
                    ref={this.textInput}
                    className="edit"
                    value={this.state.editText}
                    onChange={this.handleChange}
                    onKeyDown={this.handleKeyDown}
                    onBlur={() => this.handleSubmit()}
                />
            </li>
        );
    }
}
